<template>
    <div>
        <div style="margin: 20px 0;" class="btn_box">
            <el-button type="primary" @click="handlerAdd">添加用户</el-button>
        </div>

        <el-table :data="users" style="width: 100%;height: 500px;">
            <el-table-column label="序号" type="index" width="80px"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="电话号码" prop="phone"></el-table-column>
            <el-table-column label="创建时间" prop="create_time" :formatter="resetDate"></el-table-column>
            <el-table-column label="所属角色" prop="role_id" :formatter="formateRole"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row._id)"> 编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row._id)"> 删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <el-dialog v-model="userFormVisible" title="添加用户" width="500px">
            <el-form :model="user" ref="userFormRef" label-width="100px" label-position="right" style="width:400px"
                :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="user.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="user.password" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name" />
                </el-form-item>
                <el-form-item label="角色" prop="role_id">
                    <el-select v-model="user.role_id" placeholder="请点击选择">
                        <el-option v-for="option in roleOptions" :key="option._id" :label="option.name"
                            :value="option._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="user.phone" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary"
                        @click="user._id == null ? addData(userFormRef) : updateData(userFormRef)">确认</el-button>
                    <el-button @click="userFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, ElSelect, type FormInstance, type FormRules } from 'element-plus';
import type { userInfoData } from '@/api/user/type';
import { onMounted, ref, reactive, nextTick } from 'vue';
//引入角色小仓库
import useUserStore from '@/store/modules/user';
let useStore = useUserStore();

//自定义校验检测
const validateUserName = (_rule: any, value: any, callback: any) => {
    value = value.trim()
    const length = value && value.length;
    const pwdReg = /^[a-zA-Z0-9_]+$/;
    if (value === "") {
        callback(new Error('请输入账号'))
    } else if (length < 4 || length > 12) {
        callback(new Error('长度在4-12位字符'))
    } else if (!pwdReg.test(value)) {
        callback(new Error("账号必须是英文、数字或下划线组成"))
    } else {
        callback()
    }
}
const validatePhone = (_rule: any, value: any, callback: any) => {
    value = value.trim()
    const phoneReg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (value === "") {
        callback(new Error('请输入手机号码'))
    } else if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号码'))
    } else {
        callback()
    }
}

const users = ref<userInfoData[] | undefined>([])

const user = ref<userInfoData | undefined>({
    //@ts-ignore
    _id: null,
    username: '',
    password: '',
    name: '',
    phone: '',
    role_id: '',
})


const userFormVisible = ref(false)

const userFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
    username: [{
        required: true, validator: validateUserName, trigger: ['blur', 'change']
    }],
    password: [{
        required: true, message: '请输入密码', trigger: 'blur'
    },
    { min: 3, message: '密码长度需要大于四位', trigger: 'blur' }
    ],
    name: [{
        required: true, message: '请输入姓名', trigger: 'blur'
    }],
    role_id: [{
        required: true, message: "请输入角色", trigger: 'blur'
    }],
    phone: [{
        required: true, validator: validatePhone, trigger: ['blur', 'change']
    }],
})
//引入角色小仓库
import useRoleStore from '@/store/modules/role';
import type { roleInfoData } from '@/api/role/type';
import { formateDate } from '@/utils/dateUtils';
const roleStore = useRoleStore()
//用户数据列表

//获取用户列表
const getUserList = () => {
    useStore.getUserList({ page: currentPage.value, size: pageSize.value }).then(response => {
        users.value = useStore.users
        //@ts-ignore
        total.value = (response?.total as number)
    })
}
//打开编辑窗口
const handleEdit = (_id: string) => {
    handlerAdd()
    useStore.getUserById(_id).then(response => {
        user.value = response
    })
};

//编辑用户
const updateData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            useStore.updateUser((user.value as userInfoData)).then(_response => {
                userFormVisible.value = false
                getUserList()
            })
        } else {

        }
    })
}
const handleDelete = (_id: string) => {
    ElMessageBox.confirm(
        '确认要删除吗？',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            useStore.deleteUser(_id).then(_response => {
                getUserList()
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            })
        })
        .catch(() => {
        })
};
//角色列表
const roleOptions = ref<roleInfoData[] | undefined>([])
//获取角色列表
const getRoleList = () => {
    roleStore.roleList().then(() => {
        roleOptions.value = roleStore.roles
    })
}
//格式化角色名称方法
const formateRole = (_row: any, _colum: any, cellValue: string, _index: number) => {
    let role = roleOptions.value?.find(item => item._id == cellValue)
    return role?.name
}
//格式化日期数据
const resetDate = (
    _row: any,
    _colum: any,
    cellValue: number,
    _index: number,
) => {
    return formateDate(cellValue);
};
//当前页面
const currentPage = ref(1)
//一页显示多少数据
const pageSize = ref(5)
//总条数
const total = ref(0)
//总页数
//@ts-ignore
const totalpage = ref(1)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getUserList()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getUserList()
}
const handlerAdd = () => {
    user.value = {
        //@ts-ignore
        _id: null,
        username: '',
        password: '',
        name: '',
        phone: '',
        role_id: '',
    }
    userFormVisible.value = true
    nextTick(() => {
        userFormRef.value?.resetFields()
    })
}
const addData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            useStore.addUser((user.value as userInfoData)).then(_response => {
                userFormVisible.value = false
                getUserList()
            })
        } else {

        }
    })
}
onMounted(() => {
    getRoleList(),
        getUserList()
})
</script>

<style scoped></style>
